package com.shen.shop;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.dom4j.io.XMLWriter;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import javax.lang.model.util.Elements;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Author:shen
 * CreateDate:2020/6/10.
 * Function:
 */
public class Shop {

    private static final String PATH = "demo34/src/products.xml";
    public static void main(String[] args) throws DocumentException {
        SAXReader saxReader=new SAXReader();
        Document read = saxReader.read(PATH);
        Element rootElement = read.getRootElement();

        //查看所有节点
       //selectAllProductEle(rootElement);

        Product product=new Product(2959,"古井贡酒5年陈酿",299.5,300,"瓶",false,"亳州");

        //增加节点
        addProductEle(product,read);

        //修改节点
        //updateProduct(product,read);

        //删除节点
        //deleteProduct(product,read);

        //购买商品
        //buyProduct(2958,100,read);

    }

    /**
     * 查询所有
     */
    public static void selectAllProductEle(Element rootElement){
        List list = rootElement.selectNodes("//product");
        for (int i=0;i<list.size();i++){
            Element element =(Element) list.get(i);
            Product product = getProduct(element);
            System.out.println(product);
        }
    }
    /**
     * 增加一个对象
     */
    public static void addProductEle(Product product,Document document) {
        Element selectProductById = selectProductById(product.getItemno(), document);
        Element selectProductByName = selectProductByName(product.getName(), document);
        if(product!=null&&selectProductById==null&&selectProductByName==null){
          //获得根节点
          Element rootElement = document.getRootElement();
          //增加节点product
          Element element=rootElement.addElement("product");
          //增加属性
          element.addAttribute("discount", String.valueOf(product.getDiscount()));
          element.addAttribute("factoryaddr", String.valueOf(product.getFactoryaddr()));
          //增加子节点
          Element itemno = element.addElement("itemno");
          Element name = element.addElement("name");
          Element price = element.addElement("price");
          Element stockcount = element.addElement("stockcount");
          Element unit = element.addElement("unit");
          //设置节点值
          itemno.setText(String.valueOf(product.getItemno()));
          name.setText(product.getName());
          price.setText(String.valueOf(product.getPrice()));
          stockcount.setText(String.valueOf(product.getStockcount()));
          unit.setText(product.getUnit());

         writeXML(document);
      }else{
          System.out.println("添加失败！");
      }
    }
    /**
     *根据输入的商品号，给出它所在的节点。
     */
    public static Element selectProductById(int  id,Document document){
        Element element = (Element) document.selectSingleNode(String.format("shop/product/itemno[text()='%s']", String.valueOf(id)));
        return element;
    }
    /**
     * 输入一个商品名，给出他的节点
     */
    public static Element selectProductByName(String name,Document document){
        Element element = (Element) document.selectSingleNode(String.format("shop/product/name[text()='%s']", name));
        return element;
    }
    /**
     * 根据节点封装product
     */
    public static Product getProduct(Element element){
        Product product=new Product();
        product.setDiscount(Boolean.parseBoolean(element.attribute("discount").getValue())) ;
        product.setFactoryaddr(element.attribute("discount").getValue()); ;
        product.setItemno(Integer.parseInt(element.elementText("itemno")));
        product.setName(element.elementText("name"));
        product.setPrice(Double.parseDouble(element.elementText("price")));
        product.setStockcount(Integer.parseInt(element.elementText("stockcount")));
        product.setUnit(element.elementText("unit"));
        return product;
    }
    /**
     * 修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量
     */
    public static void updateProduct(Product product, Document document) {
        Element element = selectProductById(product.getItemno(), document);
        if(element!=null){
            element.getParent().element("stockcount").setText(String.valueOf(product.getStockcount()));
            writeXML(document);
        }else{
            System.out.println("更新失败");
        }
    }
    /**
     * 删除商品
     */
    public static void deleteProduct(Product product, Document document)  {
        Element element = selectProductById(product.getItemno(), document);
        if(element!=null){
           document.getRootElement().remove(element.getParent());
            writeXML(document);
        }else{
            System.out.println("该商品不存在！");
        }
    }
    /**
     * 购买商品
     */
    public static Product buyProduct(int id,int size, Document document){
        Element element = selectProductById(id, document);
        Product product = getProduct(element.getParent());
        System.out.println(product);
        if(product.getStockcount()>=size){
            double sum = product.getPrice() * size;
            sum =product.getDiscount() ? sum*0.07:sum;
            System.out.println("需付："+sum);
            product.setStockcount(product.getStockcount()-size);
            updateProduct(product,document);
            return product;
        }else{
            System.out.println("商品不存在");
            return product;
        }
    }
    /**
     * 写入xml
     */
    public static void writeXML(Document document){
        //写入值
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        XMLWriter writer= null;
        try {
            writer = new XMLWriter(new FileOutputStream(PATH),format);
            writer.write(document);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
